package com.yxc.controller;

import com.yxc.entity.AppInfo;
import com.yxc.entity.AppVersion;
import com.yxc.entity.DevUser;
import com.yxc.service.AppInfoService;
import com.yxc.service.VersionService;
import com.yxc.utils.SessionUtils;
import com.yxc.vo.ResultVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/version")
public class VersionController {

    @Autowired
    VersionService versionService;

    @Autowired
    AppInfoService appInfoService;

    @GetMapping("/{appid}")
    public ResultVo getList(@PathVariable Long appid){
        List<AppVersion> list = versionService.getList(appid);
        return ResultVo.success(list);
    }

    @PostMapping("/saveOrUpdate")
    public ResultVo saveOrUpdate(AppVersion appVersion, MultipartFile file, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (file!=null && !file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if (file.getSize() > 500 * 1024 * 1024) {
                return ResultVo.error("文件大小大于500MB");
            } else if (extension.equals("apk")) {
                String realPath = request.getServletContext().getRealPath("/upload/apk");
                File savePath = new File(realPath);
                if (!savePath.exists()) {
                    savePath.mkdirs();
                }

                String fileName = UUID.randomUUID().toString().replace("-", "");
                File saveFile = new File(realPath + File.separator + fileName + "." + extension);

                try {
                    file.transferTo(saveFile);
                    appVersion.setDownloadlink("/upload/apk/" + fileName + "." + extension);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultVo.error("apk文件上传失败");
                }

            } else {
                return ResultVo.error("文件格式错误");
            }
        }

        DevUser devUser = (DevUser) SessionUtils.get(token);
        appVersion.setCreatedby(devUser.getId());
        appVersion.setCreationdate(new Date());
        appVersion.setPublishstatus(3L);

        versionService.saveOrUpdate(appVersion);
        AppInfo appInfo = new AppInfo();
        appInfo.setId(appVersion.getAppid());
        appInfo.setVersionid(appVersion.getId());
        appInfoService.saveOrUpdate(appInfo);
        return ResultVo.success("新增修改成功");
    }
}
